// src/components/bpmn-palette/utils/createElement.ts
import { defineComponent, ref } from 'vue';
import modelerStore from '../../../../../../store/modules/modeler';
import ElementFactory from 'bpmn-js/lib/features/modeling/ElementFactory';
import Create from 'diagram-js/lib/features/create/Create';

export const createElement = (ev: Event, type: string,defalutName: string, options?: any) => {
  const store = modelerStore();
  
  // 并行网关时，同时创建两个
  if (type === 'ParallelGateway' || type === 'InclusiveGateway') {
    const elementFactory = store.getModeler!.get('elementFactory');
    const modeling = store.getModeler!.get('modeling');
    const canvas = store.getModeler!.get('canvas');
    const parentElement = canvas.getRootElement();

    // 创建第一个并行网关
    const gateway1 = elementFactory.createShape({
      type: 'bpmn:InclusiveGateway',
      x: 100,
      y: 100,
    });
    
    if (options) {
      const newOptions = { icon: '/assets/bpmnIcon/parallel-gateway.svg', ...options };
      gateway1.businessObject.extended = newOptions;
    }

    modeling.createShape(gateway1, { x: 100, y: 100 }, parentElement);

    // 创建第二个并行网关
    const gateway2 = elementFactory.createShape({
      type: 'bpmn:InclusiveGateway',
      x: 300,
      y: 100,
    });

    if (options) {
      gateway2.businessObject.extended = { GatewayType: 'JoinGateway' };
    }
    modeling.createShape(gateway2, { x: 300, y: 100 }, parentElement);
  } else {
    const elementFactory = store.getModeler!.get('elementFactory');
    const create = store.getModeler!.get('create');
    const shape = elementFactory.createShape({ 
      type: `bpmn:${type}`,
      ...{} 
    });
    
    if (options) {
      const newOptions = { icon: '/assets/bpmnIcon/parallel-gateway.svg', ...options };
      shape.businessObject.extended = newOptions;
    }
    shape.businessObject.name = defalutName;
    
    // 如果是服务节点
    if (type === 'ServiceTask') {
      shape.businessObject['activiti:class'] =
        'com.zsix.system.service.listener.MachineService';
      shape.businessObject.$attrs['activiti:class'] =
        'com.zsix.system.service.listener.MachineService';
    }
    
    create.start(ev, shape);
  }
};